﻿using Himall.IServices;
using Himall.IServices.QueryModel;
using Himall.Model;
using Himall.Service;
using System.Collections.Generic;
using System.Linq;
using Himall.Entity;
using System;


namespace Himall.Service
{
    public class MemberInviteService : ServiceBase, IMemberInviteService
    {
        public void SetInviteRule(InviteRuleInfo model)
        {
            var m = Context.Set<InviteRuleInfo>().FirstOrDefault(a => a.Id == model.Id);
            if (m == null)
            {
                Context.Set<InviteRuleInfo>().Add(model);
            }
            else
            {
                m.InviteIntegral = model.InviteIntegral;
                m.RegIntegral = model.RegIntegral;

            }
            Context.SaveChanges();
        }

        string MoveImages(string image)
        {
            if (string.IsNullOrWhiteSpace(image))
            {
                return "";
            }

            var ext = image.Substring(image.LastIndexOf("."));
            //转移图片
            string relativeDir = "/Storage/Plat/MemberInvite/";
            string fileName = "Invite_Icon" + ext;
            if (image.Contains("/temp/"))//只有在临时目录中的图片才需要复制
            {
                string temp = image.Substring(image.LastIndexOf("/temp"));
                Core.HimallIO.CopyFile(temp, relativeDir + fileName, true);
                return relativeDir + fileName;
            }  //目标地址
            else
            {
                var fname = image.Substring(image.LastIndexOf("/") + 1);
                return relativeDir + fname;
            }
        }

        public InviteRuleInfo GetInviteRule()
        {
            var inviteRule = Context.Set<InviteRuleInfo>().FirstOrDefault();
            if (inviteRule == null)
            {
                InviteRuleInfo ruleInfo = new InviteRuleInfo();
                ruleInfo.InviteIntegral = 0;
                ruleInfo.RegIntegral = 0;
                ruleInfo.ShareDesc = "分享描述";
                ruleInfo.ShareRule = "分享规则";
                ruleInfo.ShareTitle = "分享标题";
                return ruleInfo;
            }
            inviteRule.ShareIcon = Core.HimallIO.GetRomoteImagePath(inviteRule.ShareIcon);
            return inviteRule;
        }


        public bool HasInviteIntegralRecord(long RegId)
        {
            return Context.Set<InviteRecordInfo>().Any(a => a.RegUserId == RegId);
        }

        public ObsoletePageModel<InviteRecordInfo> GetInviteList(InviteRecordQuery query)
        {
            int total = 0;
            ObsoletePageModel<InviteRecordInfo> result = new ObsoletePageModel<InviteRecordInfo>();
            var datasql = Context.Set<InviteRecordInfo>().AsQueryable();
            if (!string.IsNullOrEmpty(query.userName))
            {
                datasql = datasql.Where(d => d.UserName.Equals(query.userName));
            }
            datasql = datasql.GetPage(out total, query.PageNo, query.PageSize, d => d.OrderByDescending(a => a.Id));
            //数据转换
            result.Models = datasql;
            result.Total = total;
            return result;
        }

        public UserInviteModel GetMemberInviteInfo(long userId)
        {
            UserInviteModel model = new UserInviteModel();
            var query = Context.Set<InviteRecordInfo>().Where(a => a.UserId == userId);
            var PersonCount = query.Count();
            var IntergralCount = query.Sum(a => (int?)a.InviteIntegral).GetValueOrDefault();
            model.InviteIntergralCount = IntergralCount;
            model.InvitePersonCount = PersonCount;
            return model;
        }


        public void AddInviteRecord(InviteRecordInfo info)
        {
            Context.Set<InviteRecordInfo>().Add(info);
            Context.SaveChanges();
        }
        /// <summary>
        /// 获取所有邀请的下级
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public List<long> GetChilds(long  id)
        {
            List<long> ids = new List<long>();
           var r= Context.Set<InviteRecordInfo>().Where(x=>x.UserId==id);
            if (r != null && r.Count() > 0)
            {
                r.ToList().ForEach(x => {
                    if (x.RegUserId != 0)
                    {
                        ids.Add(x.RegUserId);
                        ids.AddRange(GetChilds(x.RegUserId));
                    }
                });
            }
            return ids;      
        }

        public void AddInviteIntegel(UserMemberInfo RegMember, UserMemberInfo InviteMember)
        {
            var InviteRule = GetInviteRule();
            if (InviteRule == null)
            {
                return;
            }

            if (!HasInviteIntegralRecord(RegMember.Id)) //没有过邀请得分，加积分
            {
                var factoryService = ServiceProvider.Instance<IMemberIntegralConversionFactoryService>.Create;
                var integralService = ServiceProvider.Instance<IMemberIntegralService>.Create;
                MemberIntegralRecord info = new MemberIntegralRecord();
                info.UserName = RegMember.UserName;
                info.MemberId = RegMember.Id;
                info.RecordDate = DateTime.Now;
                info.ReMark = "被邀请注册";
                info.TypeId = IntegralType.Others;
                var memberIntegral = factoryService.Create(IntegralType.Others, InviteRule.RegIntegral.Value);
                integralService.AddMemberIntegral(info, memberIntegral);

                MemberIntegralRecord info2 = new MemberIntegralRecord();
                info2.UserName = InviteMember.UserName;
                info2.MemberId = InviteMember.Id;
                info2.RecordDate = DateTime.Now;
                info2.ReMark = "邀请会员";
                info2.TypeId = IntegralType.InvitationMemberRegiste;
                var memberIntegral2 = factoryService.Create(IntegralType.InvitationMemberRegiste);
                integralService.AddMemberIntegral(info2, memberIntegral2);

                InviteRecordInfo inviteInfo = new InviteRecordInfo();
                inviteInfo.RegIntegral = InviteRule.RegIntegral.GetValueOrDefault();
                inviteInfo.InviteIntegral = InviteRule.InviteIntegral.GetValueOrDefault();
                inviteInfo.RecordTime = DateTime.Now;
                inviteInfo.RegTime = RegMember.CreateDate;
                inviteInfo.RegUserId = RegMember.Id;
                inviteInfo.RegName = RegMember.UserName;
                inviteInfo.UserId = InviteMember.Id;
                inviteInfo.UserName = InviteMember.UserName;
                AddInviteRecord(inviteInfo);
            }
        }

        private PromoterInfo GetUserByAgent(long userId, int level = 0)
        {
          
            if (userId == 0)
            {
                return null;
            }
            else
            {
             
                PromoterInfo p = new PromoterInfo();
                if (level == 0)
                {
                    p = Context.Set<PromoterInfo>().Where(x => x.UserId == userId && x.Status == PromoterStatus.Audited).FirstOrDefault();
                }
                else
                {
                    p = Context.Set<PromoterInfo>().Where(x => x.UserId == userId && x.Status == PromoterStatus.Audited && x.Level == level).FirstOrDefault();

                }
                if (p != null && p.UserId != 0)
                {
                    return p;

                }
                else
                {
                    var invite = Context.Set<InviteRecordInfo>().Where(a => a.RegUserId == userId).FirstOrDefault();
                    if (invite != null && invite.Id != 0)
                    {
                        return GetUserByAgent(invite.UserId, level);
                    }
                    else {
                        return null;
                    }
                }
            }
        }

        public void AddAgentRelationInfo(UserMemberInfo userMember)
        {
            var agent = Context.Set<AgentRelationInfo>().Where(a => a.UserId == userMember.Id).FirstOrDefault();
            if (agent == null || agent.Id == 0)
            {
                agent = new AgentRelationInfo();
                agent.UserId = userMember.Id;
                Context.Set<AgentRelationInfo>().Add(agent);               
            }
            var p = GetUserByAgent(userMember.InviteUserId.Value);//获取上面第一个代理
            if (p == null)
            {
                Context.Set<AgentRelationInfo>().Remove(agent);
            }
            else
            {
                if (p.Level == 2)
                {
                    agent.AgentTwoId = p.UserId;
                    p = GetUserByAgent(userMember.InviteUserId.Value, 1);//获取总代
                    if (p != null)
                    {
                        agent.AgentOneId = p.UserId;
                    }
                    else
                    {
                        agent.AgentOneId = 0;
                    }
                }
                else if (p.Level == 1)
                {
                    agent.AgentTwoId = 0;
                    agent.AgentOneId = p.UserId;
                }
                else
                {
                    agent.AgentOneId = 0;
                    agent.AgentTwoId = 0;
                }
            }
            Context.SaveChanges();
        }
        /// <summary>
        /// 更新用户代理关系
        /// </summary>
        /// <param name="id"></param>
        public void UpdateAgentInfo(long id)
        {            
            var list = Context.Set<AgentRelationInfo>().Where(a => a.AgentOneId == id||a.AgentTwoId==id).ToList();
            if (list != null)
            {
                list.ForEach(x=>{
                   var menber= ServiceProvider.Instance<IMemberService>.Create.GetMember(x.UserId);
                    AddAgentRelationInfo(menber);
                });
            }           
        }

        /// <summary>
        /// 更新用户代理关系
        /// </summary>
        /// <param name="id"></param>
        public void AddAgentInfo(long id)
        {
            var list = GetChilds(id);
            if (list != null)
            {
                list.ForEach(x => 
                {
                    var menber = ServiceProvider.Instance<IMemberService>.Create.GetMember(x);
                    AddAgentRelationInfo(menber);
                });
            }
        }
        /// <summary>
        /// 更新用户代理关系
        /// </summary>
        /// <param name="id"></param>
        public void DeleteAgentInfo(long id)
        {
            var list = GetChilds(id);
            if (list != null)
            {
                list.ForEach(x =>
                {
                    var menber = ServiceProvider.Instance<IMemberService>.Create.GetMember(x);
                    AddAgentRelationInfo(menber);
                });
            }
        }

        public AgentRelationInfo GetAgentInfo(long userId)
        {
            var agent = Context.Set<AgentRelationInfo>().Where(a => a.UserId == userId).FirstOrDefault();
            if (agent != null && agent.Id!= 0)
            {
                return agent;
            }
            else
            {
                return null;
            }
        }
    }
}

